/* 
 * cms，一个基于J2EE架构内容管理系统
 * Copyright © GrayRabbit Co., Ltd. All rights reserved.
 * Department:运营department
 * 更多信息请访问：
 * http://code.google.com/p/gray-rabbit-cms/
 */
package org.grayrabbit.cms.action.theme;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.grayrabbit.cms.action.common.SimpleAction;
import org.grayrabbit.cms.constant.ConstantTheme;
import org.grayrabbit.cms.constant.ConstantWebApp;
import org.grayrabbit.cms.entity.Site;
import org.grayrabbit.cms.service.site.SiteService;
import org.grayrabbit.cms.service.theme.ThemeService;
import org.grayrabbit.cms.util.FilePathSptUtil;
import org.grayrabbit.cms.util.TplFileUtil;
import org.grayrabbit.cms.vo.theme.FileBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;


/**
 * <b>ThemeAction</b> Struts2 action�?





 * @version 1.0,创建时间:2011-05-16 15:57:47 
 */
@Controller
@Scope("prototype")
public class FileAction extends SimpleAction {
	private static final long serialVersionUID = -1L;
	private static final Logger LOG = LoggerFactory.getLogger(FileAction.class); 
	private static final String SPT = File.separator;
	private static final String ASSOCIATE_OLD_PATH="associate_main_file_path";
	private static final String WINDOWS_SPT ="\\\\";
	private static final String FOLDER_UP = "up";
	private static final String FOLDER_DOWN = "down";
	private static final String FOLDER_ROOT = "root";
	private String assoFlag;
	private String selparas;
	
	@Autowired
	@Qualifier("siteServiceImpl")
	private SiteService siteService;
 
	@Autowired
	@Qualifier("themeServiceImpl")
	private ThemeService themeService;
	
	private String elementId;
	private String prefix ; 		//取值 “index”  “list” 'vote' 'survey'常量  
	private String suffix ; 		// js   css    tpl  
	//  type . contentType  二选一
	private String type   ;				//   index  cat  topic    vote survey  
	private String contentType ;			// article  soft  image  animation video        
	private boolean root;
	private String crruentpath;
	private String mark;
	private String content; 
	private FileBean bean; 
	private List<FileBean> fileBeanList=new ArrayList<FileBean>();
	
	private String selected;
	
	@Action(value="file-select")
	public String LoadFiles(){	
		String contextPath = getThemeRootpath();
		String theme = getSystemThemeRoot();
		String siteTheme = getCurrentSite().getSiteTheme();		
		boolean flag = themeService.checkUsableTheme(siteTheme);
		if(!flag){
			fileBeanList = new ArrayList<FileBean>();
			return SUCCESS;
		}
		
		String siteShortName = getCurrentSite().getSiteShortName();
		siteTheme = StringUtils.isNotBlank(siteTheme)?siteTheme:ConstantTheme.DEFAULT;  //当前站点获取 站点主题
		if(ConstantTheme.TYPE_VOTE.equalsIgnoreCase(type) || ConstantTheme.TYPE_SURVEY.equalsIgnoreCase(type)
				||ConstantTheme.TYPE_INDEX.equalsIgnoreCase(type)||ConstantTheme.TYPE_COMMENT.equalsIgnoreCase(type)){
			fileBeanList = TplFileUtil.getPageFile(contextPath, theme, siteShortName,siteTheme, type, prefix, suffix);
		}else if(ConstantTheme.TYPE_CAT.equalsIgnoreCase(type) || ConstantTheme.TYPE_TOPIC.equalsIgnoreCase(type)){
			fileBeanList = TplFileUtil.getCatTopicPageFile(contextPath, theme, siteShortName, siteTheme, type, prefix, suffix);
		}else if(ConstantTheme.CONTENT_ARTICLE.equalsIgnoreCase(contentType)||ConstantTheme.CONTENT_IMAGE.equalsIgnoreCase(contentType)
				||ConstantTheme.CONTENT_ANIMATION.equalsIgnoreCase(contentType)||ConstantTheme.CONTENT_SOFT.equalsIgnoreCase(contentType)
				||ConstantTheme.CONTENT_VIDEO.equalsIgnoreCase(contentType)
				||ConstantTheme.CONTENT_All.equalsIgnoreCase(contentType)
		){
			fileBeanList = TplFileUtil.getContentPageFile(contextPath, theme, siteShortName, siteTheme, contentType, prefix, suffix);
		}else { 
			fileBeanList = new ArrayList<FileBean>();
		}	
		for(FileBean bean :fileBeanList){
			String s = bean.getPath();
			bean.setSelectEditPath(s);
			s = s.replaceAll(WINDOWS_SPT, "/");
			bean.setPath(s);
		}
		setSelparas(selectparameters());
		return SUCCESS;
	} 
	
	@Action(value="file-manage") 
	public String themeRoot(){
		String contextPath = getThemeRootpath();
		String theme = getSystemThemeRoot();
		
		if(StringUtils.isBlank(crruentpath) || StringUtils.isBlank(mark))
			mark = FOLDER_ROOT;   //  参数异常 进入根目录
		
		if(FOLDER_DOWN.equals(mark)){  //进入下层目录 -- 参数异常 进入根目录
			if(crruentpath.indexOf(theme)==1){
				fileBeanList = TplFileUtil.loadAllFile(contextPath,crruentpath,theme);
			}else{
				mark = FOLDER_ROOT; 				
			}
		}
		if(FOLDER_UP.equals(mark)){   //进入上层目录 -- 参数异常 进入根目录
			File file = new File (contextPath+crruentpath);
			if(file.exists() && file.isDirectory()){
				crruentpath = TplFileUtil.removeEndStr(SPT+file.getName(), crruentpath);
				if(crruentpath.indexOf(theme)==1){
					fileBeanList = TplFileUtil.loadAllFile(contextPath,crruentpath,theme);
				}else{
					mark = FOLDER_ROOT; 	
				}
			}else{
				mark = FOLDER_ROOT; 	
			}
		}
		if(FOLDER_ROOT.equals(mark)){		//进入根目录
			root = true;
			crruentpath=SPT+theme;
			fileBeanList = TplFileUtil.loadAllTheme(contextPath, crruentpath);
		}
	  
		return SUCCESS;
	}
	
	
	@Action(value="file-input",results={
			@Result(name="manage",type="redirect",location="file-manage.action")
	}) 
	public String themeEdit(){	
		if(StringUtils.isBlank(crruentpath)) return "manage";
		String contextPath = getThemeRootpath();
		String theme = getSystemThemeRoot();
		File file = new File(contextPath+crruentpath); 
		if(!file.exists() || !file.isFile()) return "manage";
		try {
			bean = new FileBean();
			bean.setFileFlag(false);
			if(crruentpath.indexOf(theme+SPT+ConstantTheme.CUSTOM) != -1){
				bean.setFileFlag(true);
			}
			String content = FileUtils.readFileToString(file, "utf-8");
			bean.setName(file.getName());
			bean.setPath(crruentpath);
			bean.setParentPath(TplFileUtil.removeEndStr(SPT+file.getName(), crruentpath));
			bean.setContent(content);
		} catch (IOException e) {
		    LOG.error("读取文件异常", e);
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	@Action(value="file-update",results={
			@Result(name="manage",type="redirect",location="file-manage.action")
	}) 
	public String themeUpdate(){	
		String contextPath = getThemeRootpath();
		String theme = getSystemThemeRoot();
		
		String path = bean.getPath();
		String parentpath = bean.getParentPath(); 
		
		String  SiteShortName = getCurrentSite().getSiteShortName();
		SiteShortName = FilePathSptUtil.trimLeftAndRightSpt(SiteShortName);
		if(StringUtils.isBlank(SiteShortName)){
			return renderText("{flag:false,msg:'当前站点简称不存在不能创建对应站点目录'}");
		}
		SiteShortName=SiteShortName.toLowerCase();
		path = TplFileUtil.getCustomPath(path, theme,SiteShortName);//获取站点目录文件加名称
		String newParentpath = TplFileUtil.getCustomPath(parentpath, theme,SiteShortName);
		File parent = new File(contextPath+newParentpath);
		if(!parent.exists() || !parent.isDirectory()){			
			parent.mkdirs();
		} 
		
		File file = new File(contextPath+path);		 
		try {
			FileUtils.writeStringToFile(file, bean.getContent(), "UTF-8"); 
			return renderText("{flag:true,msg:'已经修改成功'}");	
		} catch (IOException e) {			 
			LOG.error("写文件异常", e);			 
			return renderText("{flag:false,msg:'修改异常'}");
		} 
	}
	
	@Action(value="file-edit")
	public String update(){
		String contextPath = getThemeRootpath();
		String parentpath = bean.getParentPath(); 
		String path = bean.getPath();		
		File file = new File(FilePathSptUtil.trimRightSpt(contextPath) +FilePathSptUtil.padLeftSpt(path));		
		try {
			FileUtils.writeStringToFile(file, bean.getContent(), "UTF-8");
			parentpath = parentpath.replaceAll(WINDOWS_SPT, WINDOWS_SPT+WINDOWS_SPT);
			return renderText("{flag:true,msg:'已经修改成功!',oldPath:'"+parentpath+"'}");	
		} catch (IOException e) {
			e.printStackTrace();
			LOG.error("写文件异常", e);
			return renderText("{flag:false,msg:'修改异常'");
		}  
	}
	
	@Action(value="file-associate",results={
			@Result(name="manage",type="redirect",
					location="file-manage.action")
	})
	public String associate(){
		if(StringUtils.isBlank(crruentpath))  return "manage";
		String theme = getSystemThemeRoot();
		String prefix=null;
		int point = crruentpath.lastIndexOf(TplFileUtil.POINT);
		if(point==-1){
			return "manage";
		}else{
			int index = crruentpath.lastIndexOf(SPT);
			if(index ==-1){
				return "manage";
			}
			prefix = crruentpath.substring(index+1, point);
			crruentpath = crruentpath.substring(0, index);
		}
			
		String  SiteShortName = getCurrentSite().getSiteShortName();
		SiteShortName = FilePathSptUtil.trimLeftAndRightSpt(SiteShortName);
		if(StringUtils.isBlank(SiteShortName)){
			return "manage";
		}
		SiteShortName=SiteShortName.toLowerCase(); 		
		String assoPath = TplFileUtil.getCustomPath(crruentpath, theme,SiteShortName); 		
		String contextPath = getThemeRootpath();		
		fileBeanList = TplFileUtil.getAssociateFiles(contextPath, assoPath, prefix);
		getRequest().getSession().setAttribute(ASSOCIATE_OLD_PATH,crruentpath.replace(SPT, SPT+SPT) );
		return SUCCESS;
	}
	
	@Action(value="file-delete",results={
			@Result(name="manage",type="redirect",
					location="file-manage.action")
	})
	public String fileDelete(){
		if(StringUtils.isBlank(crruentpath)) 
			return renderText("{flag:false,msg:'路径异常'}");
		int point = crruentpath.lastIndexOf(TplFileUtil.POINT);
		if(point==-1){
			return renderText("{flag:false,msg:'路径异常'}");
		}else{
//			 TODO 判断该文件是否被引用（删除）（tpl ,依据路径判断 是 站点？栏目？调查？）  hasau
			String contextPath = getThemeRootpath();
			File file = new File(contextPath+crruentpath);
			if(!file.exists() || !file.isFile()){
				return renderText("{flag:false,msg:'文件不存在'}");				
			}
			file.delete(); 
			return  renderText("{flag:true,msg:'删除成功'}");
		}
	
	}
	
	private  Site getCurrentSite(){
		Site currentSite = (Site)getSessionValue(ConstantWebApp.CURRENT_SITE);
		Site site = siteService.getSite(currentSite.getSiteId());
		return site; 
	}
	

	/**系统主题根路径 相对路径
	 * @return
	 */
	private String getSystemThemeRoot(){
		return ConstantTheme.THEME;
	}
	
	/**contextpath
	 * @return
	 */
	private String getThemeRootpath(){	 
		return  FilePathSptUtil.THEME_ROOT_PATH;
	}
    
	/**
	 * 替换模板路径中的特殊符号
	 * @param str
	 * @return
	 */
	public String getStr(String str){
		String str1 = str.replace("/", "");
		String str2 = str1.replace(".", "");
		return str2;
	}
	
	public List<FileBean> getFileBeanList() {
		return fileBeanList;
	}
	public void setFileBeanList(List<FileBean> fileBeanList) {
		this.fileBeanList = fileBeanList;
	}
	public String getPrefix() {
		return prefix;
	}
	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}
	public String getSuffix() {
		return suffix;
	}
	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getElementId() {
		return elementId;
	}

	public void setElementId(String elementId) {
		this.elementId = elementId;
	}

	public boolean isRoot() {
		return root;
	}

	public void setRoot(boolean root) {
		this.root = root;
	}


	public String getCrruentpath() {
		return crruentpath;
	}

	public void setCrruentpath(String crruentpath) {
		this.crruentpath = crruentpath;
	}
 

	public String getMark() {
		return mark;
	}

	public void setMark(String mark) {
		this.mark = mark;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	public FileBean getBean() {
		return bean;
	}

	public void setBean(FileBean bean) {
		this.bean = bean;
	}
     
	public static String toUtf8Encode(String s) {
		String r = null;
		if(s != null) {
			try {
				r = URLEncoder.encode(s, "utf-8");
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return r;
	}
	
	public static String toUtf8Decode(String s) {
		String r = null;
		if(s != null) {
			try {
				r = URLDecoder.decode(s, "utf-8");
			} catch(Exception e) {
				e.printStackTrace();
			}
		}
		return r;
	}

	public String getAssoFlag() {
		return assoFlag;
	}

	public void setAssoFlag(String assoFlag) {
		this.assoFlag = assoFlag;
	} 
	private String selectparameters(){
		StringBuffer sb = new StringBuffer(); 
		sb.append("type").append("=").append(type).append("&");
		sb.append("prefix").append("=").append(prefix).append("&");
		sb.append("suffix").append("=").append(suffix).append("&");
		sb.append("contentType").append("=").append(contentType);
		return sb.toString();
	}

	public String getSelparas() {
		return selparas;
	}

	public void setSelparas(String selparas) {
		this.selparas = selparas;
	}

	public String getSelected() {
		return selected;
	}

	public void setSelected(String selected) {
		this.selected = selected;
	}
}